<?php
if (!file_exists('../install.lock')) {
    header('Location: ../install.php');
    exit;
}
session_start();
require_once '../config.php';

// 检查是否登录
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// 获取系统设置
$settings = getSettings();

// 分页设置
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 15;
$offset = ($page - 1) * $limit;

// 批量将超时未支付订单状态更新为已过期（5分钟）
$pdo->exec("UPDATE orders SET status='expired' WHERE status='pending' AND TIMESTAMPDIFF(MINUTE, created_at, NOW()) > 5");

// 获取商品列表用于筛选
$all_products = $pdo->query("SELECT id, name FROM products ORDER BY sort_order ASC, id ASC")->fetchAll();

// 处理搜索和筛选参数
$search = trim($_GET['search'] ?? '');
$status_filter = $_GET['status'] ?? '';
$type_filter = $_GET['type'] ?? '';

// 构建where条件
$where = '1=1';
$where_count = '1=1';
$params = [];
if ($search !== '') {
    $where .= " AND o.order_no LIKE :search";
    $where_count .= " AND o.order_no LIKE :search";
    $params['search'] = "%$search%";
}
if ($status_filter !== '' && $status_filter !== 'all') {
    $where .= " AND o.status = :status";
    $where_count .= " AND o.status = :status";
    $params['status'] = $status_filter;
}
if ($type_filter !== '' && $type_filter !== 'all') {
    $where .= " AND p.duration_type = :type";
    $where_count .= " AND p.duration_type = :type";
    $params['type'] = $type_filter;
}

// 获取订单总数
$sql_count = "SELECT count(*) FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE $where_count";
$stmt_count = $pdo->prepare($sql_count);
// 只保留SQL中实际出现的参数
$real_params = [];
foreach ($params as $k => $v) {
    if (strpos($sql_count, ':'.$k) !== false) {
        $real_params[$k] = $v;
    }
}
$stmt_count->execute($real_params);
$total_orders = $stmt_count->fetchColumn();
$total_pages = ceil($total_orders / $limit);

// 获取订单列表
$sql = "SELECT o.*, p.name as product_name, p.duration_type, p.duration_value FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE $where ORDER BY o.id DESC LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
foreach ($params as $k => $v) {
    $stmt->bindValue(':' . $k, $v);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$orders = $stmt->fetchAll();

// 获取会话消息
$error = $_SESSION['error'] ?? '';
$success = $_SESSION['success'] ?? '';
unset($_SESSION['error'], $_SESSION['success']);

// 处理批量删除请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['batch_delete']) && !empty($_POST['order_ids'])) {
    $order_ids = $_POST['order_ids'];
    if (is_array($order_ids) && count($order_ids) > 0) {
        // 只删除orders表，不删除kami表
        $in = str_repeat('?,', count($order_ids) - 1) . '?';
        $stmt = $pdo->prepare("DELETE FROM orders WHERE order_no IN ($in)");
        $stmt->execute($order_ids);
        $_SESSION['success'] = '批量删除成功';
        header('Location: order_manage.php');
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title><?php echo htmlspecialchars($settings['title']); ?> - 订单管理</title>
    <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico">
    <link rel="stylesheet" type="text/css" href="../assets/css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
    <style>
    @media (max-width: 767.98px) {
        .table-responsive {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        .table-order-mobile {
            display: block;
            width: 100%;
        }
        .table-order-mobile thead { display: none; }
        .table-order-mobile tbody { display: block; }
        .table-order-mobile tr { display: block; margin-bottom: 1rem; border: 1px solid #eee; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.03); background: #fff; }
        .table-order-mobile td { display: flex; width: 100%; border: none; border-bottom: 1px solid #f2f2f2; align-items: center; padding: 0.5rem 1rem; font-size: 15px; }
        .table-order-mobile td:last-child { border-bottom: none; }
        .table-order-mobile .order-label { min-width: 80px; color: #888; font-size: 13px; margin-right: 8px; display: inline-block; }
        .table-order-mobile .order-actions { justify-content: flex-end; }
    }
    @media (min-width: 768px) {
        .table-order-mobile .order-label { display: none !important; }
    }
    </style>
</head>

<body>
<div id="lyear-preloader" class="loading">
    <div class="ctn-preloader"><div class="round_spinner"><div class="spinner"></div><img src="../assets/images/loading-logo.png" alt=""></div></div>
</div>

<div class="lyear-layout-web">
    <div class="lyear-layout-container">
        <?php $current_page = 'order_manage'; include 'navbar.php'; ?>
        
        <main class="lyear-layout-content">
            <div class="container-fluid p-t-15">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-header">
                                <h4>订单管理</h4>
                            </div>
                            <div class="card-body">
                                <?php if ($error): ?>
                                <div class="alert alert-danger" role="alert"><?php echo $error; ?></div>
                                <?php endif; ?>
                                <?php if ($success): ?>
                                <div class="alert alert-success" role="alert"><?php echo $success; ?></div>
                                <?php endif; ?>

                                <form class="row mb-4" method="get" action="">
                                    <div class="col-md-3 mb-2">
                                        <input type="text" class="form-control" name="search" placeholder="请输入订单号" value="<?php echo htmlspecialchars($search); ?>">
                                    </div>
                                    <div class="col-md-2 mb-2">
                                        <select class="form-select" name="type">
                                            <option value="all">全部类型</option>
                                            <option value="minute" <?php if($type_filter==='minute') echo 'selected'; ?>>分钟卡</option>
                                            <option value="hour" <?php if($type_filter==='hour') echo 'selected'; ?>>小时卡</option>
                                            <option value="day" <?php if($type_filter==='day') echo 'selected'; ?>>天卡</option>
                                            <option value="week" <?php if($type_filter==='week') echo 'selected'; ?>>周卡</option>
                                            <option value="month" <?php if($type_filter==='month') echo 'selected'; ?>>月卡</option>
                                            <option value="season" <?php if($type_filter==='season') echo 'selected'; ?>>季卡</option>
                                            <option value="year" <?php if($type_filter==='year') echo 'selected'; ?>>年卡</option>
                                            <option value="forever" <?php if($type_filter==='forever') echo 'selected'; ?>>永久卡</option>
                                        </select>
                                    </div>
                                    <div class="col-md-2 mb-2">
                                        <select class="form-select" name="status">
                                            <option value="all">全部状态</option>
                                            <option value="pending" <?php if($status_filter==='pending') echo 'selected'; ?>>待支付</option>
                                            <option value="paid" <?php if($status_filter==='paid') echo 'selected'; ?>>已支付</option>
                                            <option value="expired" <?php if($status_filter==='expired') echo 'selected'; ?>>已过期</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3 mb-2">
                                        <button type="submit" class="btn btn-primary w-100">搜索/筛选</button>
                                    </div>
                                </form>

                                <form id="batch-delete-form" method="post" action="">
                                    <!-- 批量删除按钮放到表格上方 -->
                                    <div class="mb-3">
                                        <button type="button" class="btn btn-danger" id="batch-delete-btn">批量删除</button>
                                    </div>
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-hover table-order-mobile">
                                            <thead>
                                                <tr>
                                                    <th><input type="checkbox" id="check-all"></th>
                                                    <!--<th>ID</th>-->
                                                    <th>订单号</th>
                                                    <th>商品</th>
                                                    <th>数量</th>
                                                    <th>金额</th>
                                                    <th>状态</th>
                                                    <th>创建时间</th>
                                                    <th>支付时间</th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($orders)): ?>
                                                <tr><td colspan="10" class="text-center">无</td></tr>
                                                <?php else: ?>
                                                <!-- 移动端全选框 -->
                                                <tr class="d-md-none" style="display:block;background:none;box-shadow:none;border:none;margin-bottom:0;">
                                                    <td colspan="10" style="padding:0.5rem 1rem; border:none; background:none;">
                                                        <label style="font-weight:bold;"><input type="checkbox" id="check-all"> 全选</label>
                                                    </td>
                                                </tr>
                                                <?php foreach ($orders as $order): ?>
                                                <tr>
                                                    <td style="display:flex;align-items:center;"><input type="checkbox" name="order_ids[]" value="<?php echo htmlspecialchars($order['order_no']); ?>"></td>
                                                    <td><span class="order-label">订单号</span><?php echo htmlspecialchars($order['order_no']); ?></td>
                                                    <td><span class="order-label">商品</span>
                                                        <?php
                                                        if (empty($order['product_name'])) {
                                                            echo '无';
                                                        } else {
                                                            $type_map = [
                                                                'minute' => '分钟',
                                                                'hour' => '小时',
                                                                'day' => '天',
                                                                'week' => '周',
                                                                'month' => '月',
                                                                'season' => '季',
                                                                'quarter' => '季',
                                                                'year' => '年',
                                                                'forever' => '永久',
                                                                // 兼容中文本身
                                                                '分钟' => '分钟',
                                                                '小时' => '小时',
                                                                '天' => '天',
                                                                '周' => '周',
                                                                '月' => '月',
                                                                '季' => '季',
                                                                '年' => '年',
                                                                '永久' => '永久'
                                                            ];
                                                            $type = $type_map[$order['duration_type']] ?? $order['duration_type'];
                                                            if ($order['duration_type'] === 'forever' || $order['duration_type'] === '永久') {
                                                                echo '永久卡';
                                                            } else {
                                                                echo $type . '卡(' . $order['duration_value'] . $type . ')';
                                                            }
                                                        }
                                                        ?>
                                                    </td>
                                                    <td><span class="order-label">数量</span><?php echo $order['quantity']; ?></td>
                                                    <td><span class="order-label">金额</span>￥<?php echo number_format($order['total_amount'], 2); ?></td>
                                                    <td><span class="order-label">状态</span><?php echo getOrderStatusBadge($order['status']); ?></td>
                                                    <td><span class="order-label">创建</span><?php echo $order['created_at']; ?></td>
                                                    <td><span class="order-label">支付</span><?php echo $order['paid_at'] ?? 'N/A'; ?></td>
                                                    <td class="order-actions"><button class="btn btn-sm btn-info" type="button" onclick='showKami(<?php echo json_encode($order["kami_list"]); ?>)'>查看卡密</button></td>
                                                </tr>
                                                <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </form>

                                <!-- 分页 -->
                                <nav>
                                  <ul class="pagination justify-content-center">
                                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                      <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                    </li>
                                    <?php endfor; ?>
                                  </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- 卡密展示模态框 -->
<div class="modal fade" id="kamiModal" tabindex="-1" aria-labelledby="kamiModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="kamiModalLabel">订单卡密</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <textarea class="form-control" id="kami-list" rows="10" readonly></textarea>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" id="copy-kami-btn" style="display:none;">复制卡密</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript" src="../assets/js/popper.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/perfect-scrollbar.min.js"></script>
<script type="text/javascript" src="../assets/js/main.min.js"></script>
<script>
function showKami(kami_list) {
    if (kami_list) {
        $('#kami-list').val(kami_list);
        $('#copy-kami-btn').show();
    } else {
        $('#kami-list').val('该订单未支付或卡密为空。');
        $('#copy-kami-btn').hide();
    }
    $('#kamiModal').modal('show');
}

// 修复移动端全选功能
$(document).on('change', '#check-all', function() {
    $('input[name="order_ids[]"]').prop('checked', this.checked);
});
// 批量删除按钮
$('#batch-delete-btn').on('click', function() {
    var checkedBoxes = $('input[name="order_ids[]"]:checked');
    var checked = checkedBoxes.length;
    if (checked === 0) {
        alert('请先选择要删除的订单！');
        return;
    }
    // 检查是否包含已支付订单
    var hasPaid = false;
    checkedBoxes.each(function() {
        var row = $(this).closest('tr');
        var statusText = row.find('td').eq(5).text(); // 第6列为状态
        if (statusText.indexOf('已支付') !== -1) {
            hasPaid = true;
            return false;
        }
    });
    var msg = hasPaid
        ? '确定要删除选中的订单吗？\n\n删除已支付订单不会删除已生成的卡密，但之后无法通过订单号或取卡密码查询卡密。'
        : '确定要删除选中的订单吗？';
    if (confirm(msg)) {
        $('#batch-delete-form').append('<input type="hidden" name="batch_delete" value="1">').submit();
    }
});

$('#copy-kami-btn').on('click', function() {
    var kami = $('#kami-list').val();
    if (kami) {
        navigator.clipboard.writeText(kami).then(function() {
            alert('卡密已复制到剪贴板');
        }, function() {
            alert('复制失败，请手动复制');
        });
    }
});
</script>
</body>
</html>
<?php
function getOrderStatusBadge($status) {
    switch ($status) {
        case 'paid':
            return '<span class="badge bg-success">已支付</span>';
        case 'pending':
            return '<span class="badge bg-warning">待支付</span>';
        case 'expired':
            return '<span class="badge bg-secondary">已过期</span>';
        default:
            return '<span class="badge bg-light">未知</span>';
    }
}
?> 